//package com.dragee.modules.sys.controller;
//
//import cn.hutool.core.util.StrUtil;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.dragee.common.R;
//import com.dragee.common.VerifyParam;
//import com.dragee.common.core.domain.AjaxResult;
//import com.dragee.config.exception.AuthErrorType;
//import com.dragee.config.exception.AuthException;
//import com.dragee.config.exception.BusinessErrorType;
//import com.dragee.config.exception.BusinessException;
//import com.dragee.config.shiro.AuthToken;
//import com.dragee.constants.AuthConstants;
//import com.dragee.modules.sys.dto.TokenDTO;
//import com.dragee.modules.sys.entity.*;
//import com.dragee.modules.sys.po.RolePo;
//import com.dragee.modules.sys.service.ISysMenuService;
//import com.dragee.modules.sys.service.ISysRoleService;
//import com.dragee.modules.sys.service.UserRoleService;
//import com.dragee.modules.sys.service.UserService;
//import com.dragee.modules.sys.service.impl.PermissionService;
//import com.dragee.modules.sys.vo.LoginVo;
//import com.dragee.modules.sys.vo.RegisteredVo;
//import com.dragee.modules.sys.vo.UpdatePasswordVo;
//import com.dragee.utils.LoginUserUtil;
//import com.dragee.utils.TokenUtil;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import org.apache.shiro.SecurityUtils;
//import org.apache.shiro.authc.AuthenticationToken;
//import org.apache.shiro.crypto.hash.Sha256Hash;
//import org.apache.shiro.subject.Subject;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.Arrays;
//import java.util.List;
//import java.util.Set;
//
///**
// * @author tys on 11/10/20
// */
//@RestController
//@Api(tags = "SYS - 登陆")
//public class LoginController {
//    @Autowired
//    private UserService userService;
//    @Autowired
//    private PermissionService permissionService;
//    @Autowired
//    private ISysMenuService menuService;
//    @Autowired
//    private ISysRoleService sysRoleService;
//    @Autowired
//    private UserRoleService userRoleService;
//
//    @ApiOperation("登陆")
//    @PostMapping("/login")
//    public R login (@RequestBody LoginVo loginVo) {
//        String tokenStr;
//        AuthenticationToken token;
//        Subject subject = SecurityUtils.getSubject();
//
//        // 参数校验
//        if (StrUtil.isBlank(loginVo.getUsername()) || StrUtil.isBlank(loginVo.getPassword()) || StrUtil.isBlank(loginVo.getType()))
//        {
//            throw new BusinessException(BusinessErrorType.INVALID_PARAMS);
//        }
//        // 校验clientId
//        if (!Arrays.asList(AuthConstants.CLIENTS).contains(loginVo.getType())) {
//            throw new AuthException(AuthErrorType.NO_SUPPORT_CLIENT);
//        }
//        // 传入的密码加密
//        String password = new Sha256Hash(loginVo.getPassword(), AuthConstants.SLAT_PWD).toHex();
//
//        // 根据用户名密码去数据库比对用户 获取LoginUser
//        UserEntity user = userService.getOne(new QueryWrapper<UserEntity>().eq("username", loginVo.getUsername()), false);
//        if (user == null) {
//            throw new AuthException(AuthErrorType.USERNAME_NO_EXIST_ERROR);
//        }
//        if (user.getStatus().equals("0")) {
//            throw new AuthException(AuthErrorType.USERNAME_LOCK_ERROR);
//        }
//        /*特殊处理*/
//        SysRole role = sysRoleService.getRoleByUserId(user.getUserId().toString());
//        if (role == null) {
//            throw new AuthException(AuthErrorType.USERNAME_NO_ROLE_ERROR);
//        }
//        if (!role.getRoleKey().equals(loginVo.getType())) {
//            throw new AuthException(801, "当前账号无权限登录该角色");
//        }
//
//        LoginUser loginUser = userService.getLoginUser(loginVo.getUsername(), password);
//        if (loginUser == null) {
//            throw new AuthException(AuthErrorType.USERNAME_OR_PASSWORD_ERROR);
//        }
//        loginUser.setType(loginVo.getType());
//        /* loginUser 插入权限 permisstion */
//        loginUser.setPermissions(permissionService.getMenuPermissions(user.getUserId()));
//        loginUser.setRole(new RolePo(role));
//        // 将loginUser对象放到token中
//        tokenStr = TokenUtil.createToken(loginUser, AuthConstants.TOKEN_EXPIRE);
//        // 用户登陆 返回token
//        token = new AuthToken(tokenStr);
//        /*核心 调用认证方法*/
//        try  {
//            subject.login(token);
//            TokenDTO dto = new TokenDTO(AuthConstants.JWT_TOKEN_HEADER,
//                    AuthConstants.JWT_TOKEN_PREFIX + tokenStr,
//                    loginUser.getUserId(),
//                    loginUser.getUsername(),
//                    loginUser.getRole().getRoleName(),
//                    loginUser.getRole());
//
//            return R.ok().put("data", dto);
//        } catch (BusinessException e) {
//            return R.error(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            return R.error();
//        }
//    }
//
//    @ApiOperation("修改密码")
//    @PostMapping("/update-password")
//    public R updatePassword (@RequestBody UpdatePasswordVo vo) {
//
//        // 传入的密码加密
//        String password = new Sha256Hash(vo.getOldPassword(), AuthConstants.SLAT_PWD).toHex();
//        // 根据用户名密码去数据库比对用户 获取LoginUser
//        LoginUser loginUser = userService.getLoginUser(vo.getUsername(), password);
//        if (loginUser == null) {
//            //比对失败
//            throw new AuthException(AuthErrorType.USERNAME_PASSWORD_ERROR);
//        }
//        userService.updatePassword(vo);
//        return R.ok();
//    }
//
//    @GetMapping("getInfo")
//    @ApiOperation("获取当前登陆人权限和菜单")
//    public AjaxResult userInfo () {
//        LoginUser loginUser = LoginUserUtil.getLoginUser();
//        // 角色集合
//        Set<String> roles = permissionService.getRolePermission(loginUser.getUserId());
//        // 权限集合
//        Set<String> permissions = permissionService.getMenuPermissions(loginUser.getUserId());
//        AjaxResult ajax = AjaxResult.success();
//        ajax.put("user", loginUser);
//        ajax.put("roles", roles);
//        ajax.put("permissions", permissions);
//        return ajax;
//    }
//
//    @GetMapping("getRouters")
//    @ApiOperation("获取Router")
//    public AjaxResult getRouters()
//    {
//        Long userId = LoginUserUtil.getLoginUser().getUserId();
//        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
//        return AjaxResult.success(menuService.buildMenus(menus));
//    }
//
//    @PostMapping("/register")
//    @ApiOperation("注册")
//    public R register(@RequestBody RegisteredVo vo){
//        VerifyParam.notNull(vo);
//        vo.setPassword(new Sha256Hash(vo.getPassword(), AuthConstants.SLAT_PWD).toHex());
//        UserEntity user = new UserEntity(vo);
//        userService.saveOrUpdate(user);
//        SysRole role = sysRoleService.getRoleByKey(vo.getType());
//        if (role == null) {
//            throw new AuthException(801, "角色不存在");
//        }
//        userRoleService.save(new SysUserRole(user.getUserId(), role.getRoleId()));
//        return R.ok();
//    }
//}
//
//
